package com.onion.utils.utils;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESUtils {

    private static Logger logger = LoggerFactory.getLogger(AESUtils.class);

    private static final String KEY_ALGORITHM = "AES/CBC/NoPadding";
    private static final String ENCODING = "utf-8";         //编码

    /**
     * AES base64加密：对cipherKey进行默认处理，符合密钥要求
     * @param content
     * @param cipherKey
     * @param ivr
     * @return
     * @throws Exception
     */
    public static String encryptBase64With16(String content, String cipherKey, String ivr) throws Exception{
        String destCipherKey = StringHelper.fixedWithTail(cipherKey, 16, '0');
        String destIvr = StringHelper.fixedWithTail(ivr, 16, '0');
        return encryptBase64(content, destCipherKey, destIvr);
    }

    public static String encryptBase64(String content, String cipherKey, String ivr) throws Exception{
        try {
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            int blockSize = cipher.getBlockSize();
            byte[] dataBytes = content.getBytes();
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }
            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
            SecretKeySpec keyspec = new SecretKeySpec(cipherKey.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(ivr.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);
            return new Base64().encodeToString(encrypted);
        }catch (Exception exp){
            logger.error("AES加密出错: content={}, cipherKey={}, ivr={}", content, cipherKey, ivr, exp);
            throw new RuntimeException("AES加密失败:" + exp.getMessage());
        }
    }

    /**
     * AES解密：对cipherKey进行默认处理，符合密钥要求
     * @param cipherText
     * @param cipherKey
     * @param ivr
     * @return
     * @throws Exception
     */
    public static String decryptBase64With16(String cipherText, String cipherKey, String ivr) throws Exception{
        String destCipherKey = StringHelper.fixedWithTail(cipherKey, 16, '0');
        String destIvr = StringHelper.fixedWithTail(ivr, 16, '0');
        return decryptBase64(cipherText, destCipherKey, destIvr);
    }

    /**
     * AES解密
     * @param cipherText AES加密密文
     * @return 明文
     */
    public static String decryptBase64(String cipherText, String cipherKey, String ivr) throws Exception{
        try {
            byte[] srcCipherText = new Base64().decode(cipherText);
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            SecretKeySpec keyspec = new SecretKeySpec(cipherKey.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(ivr.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
            byte[] original = cipher.doFinal(srcCipherText);
            String originalString = new String(original);
            return originalString;
        } catch (Exception exp) {
            logger.error("AES解密出错: cipherText={}, cipherKey={}, ivr={}", cipherText, cipherKey, ivr, exp);
            throw new RuntimeException("AES解密失败:" + exp.getMessage());
        }
    }

    public static void main(String[] args) throws Exception{

        encryptBase64With16("1231231", "2222", "1111");

        String content = "zhouyawen";
        String ivr = "dufy20170329java";
        //String cipherKey = DigestUtil.md5Hex16("houlf");
        String cipherKey = "dufy20170329java";
        String cipherText = encryptBase64(content, cipherKey, ivr);

        //wNXhGYZqC7gwQp0sGZOUfg==
        String plainText = decryptBase64(cipherText, cipherKey, ivr);
        System.out.println(plainText + "------" + plainText.length());
        plainText = plainText.trim();
        System.out.println(plainText + "------" + plainText.length());
    }

}